package com.fjh.springboot_01.service.impl;

import com.fjh.springboot_01.mapper.LessonFavoriteMapper;
import com.fjh.springboot_01.mapper.LessonMapper;
import com.fjh.springboot_01.pojo.lesson.Lesson;
import com.fjh.springboot_01.pojo.lesson.LessonFavorite;
import com.fjh.springboot_01.service.LessonFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class LessonFavoriteServiceImpl implements LessonFavoriteService {
    @Autowired
    private LessonFavoriteMapper lessonFavoriteMapper;
    
    @Autowired
    private LessonMapper lessonMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void favorite(Integer lessonId, Integer userId) {
        // 检查是否已经收藏
        if (isFavorited(lessonId, userId)) {
            return;
        }

        // 添加收藏记录
        LessonFavorite lessonFavorite = new LessonFavorite();
        lessonFavorite.setLessonId(lessonId);
        lessonFavorite.setUserId(userId);
        lessonFavorite.setCreateTime(LocalDateTime.now());
        lessonFavoriteMapper.add(lessonFavorite);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unfavorite(Integer lessonId, Integer userId) {
        lessonFavoriteMapper.delete(lessonId, userId);
    }

    @Override
    public boolean isFavorited(Integer lessonId, Integer userId) {
        return lessonFavoriteMapper.exists(lessonId, userId) > 0;
    }

    @Override
    public Integer getFavoriteCount(Integer lessonId) {
        return lessonFavoriteMapper.count(lessonId);
    }
    
    @Override
    public List<Lesson> getUserFavorites(Integer userId) {
        // 获取用户收藏的课程ID列表
        List<Integer> lessonIds = lessonFavoriteMapper.getUserFavoriteIds(userId);
        
        // 如果没有收藏记录，返回空列表
        if (lessonIds == null || lessonIds.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 根据ID列表获取课程详情
        return lessonMapper.findByIds(lessonIds);
    }
}